package org.fhawk.tinyspring;

import org.apache.commons.lang.StringUtils;
import org.fhawk.tinyspring.core.ClassScanner;
import org.fhawk.tinyspring.core.ConfigHelper;
import org.fhawk.tinyspring.core.imp.DefaultClassScanner;
import org.fhawk.tinyspring.util.ObjectUtil;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by tuo on 8/17/2016.
 */
public class InstantFactory {

    private static final ConcurrentHashMap<String, Object> cache = new ConcurrentHashMap<>();

    private static final String CLASS_SCANNER = "org.fhawk.tinySpring.class.scanner";

    private InstantFactory() {
    }

    /**
     * 获取类扫描器
     *
     * @return
     */
    public static ClassScanner getClassScanner() {
        return getInstance(CLASS_SCANNER, DefaultClassScanner.class);
    }


    public static <T> T getInstance(String key, Class<T> defaultImplClass) {
        if (cache.contains(key)) {
            return (T) cache.get(key);
        }
        String implClassName = ConfigHelper.getString(key);
        if (StringUtils.isEmpty(implClassName)) {
            implClassName = defaultImplClass.getName();
        }
        T instance = ObjectUtil.newInstance(implClassName);
        if (null != instance) {
            cache.put(key, instance);
        }
        return instance;
    }
}
